'use strict';

const Controller = require('egg').Controller;
class AuthController extends Controller {
  /**
   * 用户注册
   * POST /api/auth/register
   */
  async register() {
    const { ctx, service } = this;
    const { username, email, password, role } = ctx.request.body;

    const result = await service.auth.register({ username, email, password, role });
    ctx.body = result;
  }

  /**
   * 用户登录
   * POST /api/auth/login
   */
  async login() {
    const { ctx, service } = this;
    const { username, password, role } = ctx.request.body;

    // 根据角色调用不同的登录方法
    const result = await service.auth.login({ username, password }, role);
    ctx.body = result;
  }

  /**
   * 获取当前用户信息
   * GET /api/auth/user
   */
  async getUserInfo() {
    const { ctx, service } = this;
    const { token } = ctx.request.headers;

    // 验证token
    const tokenData = service.auth.verifyToken(token);

    if (!tokenData) {
      ctx.body = {
        success: false,
        message: '未登录或token无效'
      };
      return;
    }

    // 获取用户信息
    const result = await service.auth.getUserInfo(tokenData.userId);
    ctx.body = result;
  }

  /**
   * 获取所有用户（仅用于调试）
   * GET /api/auth/users
   */
  async getAllUsers() {
    const { ctx, service } = this;

    const result = await service.auth.getAllUsers();
    ctx.body = result;
  }

  /**
   * 更新用户资料
   * PUT /api/auth/profile
   */
  async updateProfile() {
    const { ctx, service } = this;
    const { token } = ctx.request.headers;
    const updateData = ctx.request.body;

    // 验证token
    const tokenData = service.auth.verifyToken(token);

    if (!tokenData) {
      ctx.body = {
        success: false,
        message: '未登录或token无效'
      };
      return;
    }

    // 更新资料
    const result = await service.auth.updateProfile(tokenData.userId, updateData);
    ctx.body = result;
  }

  /**
   * 修改密码
   * PUT /api/auth/password
   */
  async changePassword() {
    const { ctx, service } = this;
    const { token } = ctx.request.headers;
    const passwordData = ctx.request.body;

    // 验证token
    const tokenData = service.auth.verifyToken(token);

    if (!tokenData) {
      ctx.body = {
        success: false,
        message: '未登录或token无效'
      };
      return;
    }

    // 修改密码
    const result = await service.auth.changePassword(tokenData.userId, passwordData);
    ctx.body = result;
  }
}

module.exports = AuthController;

